package com.hsj.common.gateway.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.hsj.common.gateway.constants.Constants;
import com.hsj.common.gateway.entity.GatewayDo;
import com.hsj.common.gateway.service.GatewayService;
import com.hsj.common.gateway.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName : LoadRouter
 * @Description :
 * @Author : 康仕球
 * @Date: 2023-08-30 22:10
 */
@EnableScheduling
@Component
public class AutoLoadRouter {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private GatewayService gatewayService;

    @Scheduled(cron="0 */10 * * * ?")
    public void cron(){
        // 定时检查网关是否有更新
        String s = redisUtil.getString(Constants.GATEWAY_KEY);
        if (StringUtils.isNotBlank(s)) {
            // 更新网关
            List<GatewayDo> list = JSON.parseArray(s, GatewayDo.class);
            for (GatewayDo gdo : list) {
                gatewayService.loadRouter(gdo);
            }
            // 删除Key
            redisUtil.delKey(Constants.GATEWAY_KEY);
        }
    }

}
